package com.wz.leetcode.array;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author : Wang Zhen.
 * @Date : Created in 16:40 2022/9/24
 * @Description :
 * @Modified By   :
 * @Version :
 */
public class N0001_TwoSum {
    public static int[] twoSum_v1(int[] nums, int target) {
        int[] ans = new int[2];
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; ++i) {
            map.put(nums[i], i);
        }
        for (int i = 0; i < nums.length; ++i) {
            // 这里注意后面第二条件，一个数只能用一次
            if (map.get(target - nums[i]) != null && map.get(target - nums[i]) != i) {
                ans[0] = i;
                ans[1] = map.get(target - nums[i]);
                return ans;
            }
        }
        return null;
    }

    public static int[] twoSum_v2(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; ++i) {
            if (map.containsKey(target - nums[i])) {
                return new int[]{map.get(target - nums[i]), i};
            }
            map.put(nums[i], i);
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(twoSum_v2(new int[]{2, 7, 11, 15}, 9)));
        System.out.println(Arrays.toString(twoSum_v2(new int[]{3, 2, 4}, 6)));
        System.out.println(Arrays.toString(twoSum_v2(new int[]{3, 2, 4}, 8)));
        System.out.println(Arrays.toString(twoSum_v2(new int[]{3, 3}, 6)));
    }
}
